package io.github.iogogogo.commons.util;

import io.github.iogogogo.commons.support.Enumerator;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created by tao.zeng on 2024/11/7.
 */
public class EnumUtils {

    public static <E extends Enum<?> & Enumerator> Map<Integer, String> enumToMap(Class<E> enumClazz) {
        // 合并时检查 key 是否重复
        BinaryOperator<String> merge = (u, v) -> {
            throw new IllegalStateException(String.format("Duplicate key %s", u));
        };
        Enumerator[] enumConstants = enumClazz.getEnumConstants();
        return Stream.of(enumConstants)
                .collect(Collectors.toMap(Enumerator::value,
                        Enumerator::description,
                        merge, LinkedHashMap::new));

    }

    public static <E extends Enum<?> & Enumerator> Optional<E> getEnumByValue(Class<E> enumClazz, final Integer value) {

        return Stream.of(enumClazz.getEnumConstants())
                .filter(enumerator -> Objects.equals(enumerator.value(), value))
                .findAny();
    }
}
